package m.common.model.util;

import api.model.ApiColumn;
import api.model.ApiTable;
import api.util.ApiConvertDataSupport;
import com.alibaba.fastjson.JSONObject;
import m.system.cache.CacheUtil;
import m.system.db.DBManager;
import m.system.exception.MException;
import m.system.util.ArrayUtil;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class TableUpdateUtil {
    /**
     * 插入table表 1:apiTable.oid  2:Map<name,object>
     */
    public static int insertModel(String tableOid, Map<String,Object> data) throws MException {
        ApiTable table=CacheUtil.get(ApiTable.class,tableOid);
        if(!"N".equals(table.getSource())) throw new MException(TableUpdateUtil.class,"该方法只适用于自建表");
        List<ApiColumn> cols=CacheUtil.getList(ApiColumn.class,tableOid);
        StringBuilder fieldString=new StringBuilder("oid");
        StringBuilder valueString=new StringBuilder("?");
        List<Object> valueParams= new ArrayList<>();
        valueParams.add(data.get("oid"));
        Date t=new Date();
        for(ApiColumn col : cols){
            String key=col.getName();
            if(key.equals("oid")) continue;
            if(key.equals("sysCreateTime")||key.equals("sys_create_time")||key.equals("sysUpdateTime")||key.equals("sys_update_time")){
                data.put(key,t);
            }
            if(null!=data.get(key)){
                fieldString.append(",").append(key);
                valueString.append(",?");
                if(ObjectUtil.notEmptyOid(col.getModelTable())){
                    Object obj=data.get(key);
                    if(obj instanceof JSONObject){
                        valueParams.add(((JSONObject)obj).get("oid"));
                    }else if(obj instanceof Map){
                        valueParams.add(((Map<String,Object>)obj).get("oid"));
                    }else{
                        valueParams.add(obj);
                    }
                }else {
                    valueParams.add(data.get(key));
                }
            }
        }
        StringBuilder sql=new StringBuilder("INSERT INTO ").append(table.getOid());
        sql.append("(").append(fieldString).append(") VALUES(").append(valueString).append(")");
        try {
            int num=DBManager.executeUpdate(sql.toString(), valueParams.toArray(new Object[]{}));
            ApiConvertDataSupport.addTableUpdate(tableOid, (String) data.get("oid"));
            return num;
        } catch (Exception e) {
            throw new MException(ModelUpdateUtil.class,"全量插入失败!"+e.getMessage());
        }
    }
    /**
     * 更新table表 1:apiTable.oid  2:Map<name,object>
     */
    public static int updateModel(String tableOid, Map<String,Object> data) throws MException {
        return updateModel(tableOid,data,null);
    }
    /**
     * 更新table表 1:apiTable.oid  2:Map<name,object> 3:需要更新的字段
     */
    public static int updateModel(String tableOid, Map<String,Object> data,String... fields) throws MException {
        boolean flag= null != fields;
        ApiTable table=CacheUtil.get(ApiTable.class,tableOid);
        if(!"N".equals(table.getSource())) throw new MException(TableUpdateUtil.class,"该方法只适用于自建表");
        if(StringUtil.isSpace((String) data.get("oid"))) throw new MException(TableUpdateUtil.class,"主键为空");
        List<ApiColumn> cols=CacheUtil.getList(ApiColumn.class,tableOid);
        StringBuilder fieldString=new StringBuilder();
        String whereString = " WHERE oid=?";
        List<Object> valueParams= new ArrayList<>();
        Date t=new Date();
        boolean updateTime=false;
        for(ApiColumn col : cols) {
            String key=col.getName();
            if(key.equals("sysUpdateTime")||key.equals("sys_update_time")){
                updateTime=true;
                data.put(key,t);
            }
            if(!flag||updateTime|| ArrayUtil.isContain(fields, key)){
                fieldString.append(",").append(key).append("=?");
                if(ObjectUtil.notEmptyOid(col.getModelTable())){
                    Object obj=data.get(key);
                    if(obj instanceof JSONObject){
                        valueParams.add(((JSONObject)obj).get("oid"));
                    }else if(obj instanceof Map){
                        valueParams.add(((Map<String,Object>)obj).get("oid"));
                    }else{
                        valueParams.add(obj);
                    }
                }else {
                    valueParams.add(data.get(key));
                }
            }
        }
        if(fieldString.length()<=0){
            throw new MException(TableUpdateUtil.class,"没有更新的属性!");
        }
        StringBuilder sql=new StringBuilder("UPDATE ").append(table.getOid());
        sql.append(" SET ").append(fieldString.substring(1)).append(whereString);

        try {
            valueParams.add(data.get("oid"));
            int num=DBManager.executeUpdate(sql.toString(),valueParams.toArray(new Object[]{}));
            ApiConvertDataSupport.addTableUpdate(tableOid, (String) data.get("oid"));
            return num;
        } catch (Exception e) {
            throw new MException(ModelUpdateUtil.class,"更新失败!"+e.getMessage());
        }
    }
    /**
     * 删除数据
     */
    public static int deleteModel(String tableOid,String oid) throws MException {
        ApiTable table=CacheUtil.get(ApiTable.class,tableOid);
        if(!"N".equals(table.getSource())) throw new MException(TableUpdateUtil.class,"该方法只适用于自建表");
        if(StringUtil.isSpace(oid)) throw new MException(TableUpdateUtil.class,"主键为空");
        StringBuilder sql=new StringBuilder("DELETE FROM ").append(table.getOid());
        sql.append(" WHERE oid=?");
        try {
            //数据转换支撑记录
            ApiConvertDataSupport.addTableDelete(tableOid,oid);
            return DBManager.executeUpdate(sql.toString(),oid);
        } catch (Exception e) {
            throw new MException(ModelUpdateUtil.class,"删除操作失败!"+e.getMessage());
        }
    }
}
